from django.shortcuts import render, redirect, HttpResponse
from django.urls import reverse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt  # 免除csrf token验证  语法糖

from web.forms.wiki import WikiModelForm
from web import models

from utils.encrypt import uid
from utils.tencent.cos import upload_file


def wiki(request, project_id):
    """ 文档首页 """
    wiki_id = request.GET.get('wiki_id')
    # if not wiki_id or wiki_id.isdecimal():  # 判断是否存在或者是否是十进制的小数 不是就是    # 否则就是访问的是wiki页面
    if not wiki_id or not wiki_id.isdigit():  # 判断是否存在或者是否是十进制的小数 不是就是    # 否则就是访问的是wiki页面
        return render(request, 'wiki.html')

        # 有值就是文章详细页面
    wiki_object = models.Wiki.objects.filter(id=wiki_id, project_id=project_id).first()
    return render(request, 'wiki.html', {'wiki_object': wiki_object})


def wiki_add(request, project_id):
    """ wiki 添加 """
    if request.method == 'GET':
        form = WikiModelForm(request)
        return render(request, 'wiki_add.html', {'form': form})

    form = WikiModelForm(request, data=request.POST)
    if form.is_valid():
        # 用户是否选择了父文章
        # print(form.instance.parent, form.instance.parent.depth)
        # if form.instance.parent:
        if form.instance.parent:
            # 自己的深度等于父级深度+1
            form.instance.depth = form.instance.parent.depth + 1
            # print(form.instance.depth, form.instance.parent.depth)
        else:
            form.instance.depth = 1

        form.instance.project = request.bug_platform.project  # ===
        # form.instance.project_id = project_id  # 表单中没有输入 所以保存的时候主动写
        form.save()

        # wiki首页地址
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)

    return render(request, 'wiki_add.html', {'form': form})


def wiki_catalog(request, project_id):
    """ wiki目录 """
    # 获取数据库当前项目的全部数据的id和标题和父级id
    # data = models.Wiki.objects.filter(project_id=project_id).values_list('id', 'title')
    # data 是queryset对象 里面是元组
    # data = models.Wiki.objects.filter(project=request.bug_platform.project).values_list('id', 'title', 'parent_id')

    # data 是queryset对象 里面是字典
    data = models.Wiki.objects.filter(project=request.bug_platform.project).values('id', 'title', 'parent_id').order_by('depth', 'id')
    # data = models.Wiki.objects.filter(project=request.bug_platform.project).values('id', 'title', 'parent_id')
    # json.dumps(data) 是不可以的
    return JsonResponse({'status': True, 'data': list(data)})


def wiki_delete(request, project_id, wiki_id):
    """ 删除wiki """
    models.Wiki.objects.filter(project_id=project_id, id=wiki_id).delete()
    # wiki首页地址
    url = reverse('wiki', kwargs={'project_id': project_id})
    return redirect(url)


def wiki_edit(request, project_id, wiki_id):
    """ wiki文章编辑 """
    # 获取要编辑的文章对象
    wiki_object = models.Wiki.objects.filter(project_id=project_id, id=wiki_id).first()
    # 对象不存在就返回首页
    if not wiki_object:
        url = reverse('wiki', kwargs={'project_id': project_id})
        return redirect(url)

    if request.method == "GET":
        form = WikiModelForm(request, instance=wiki_object)
        return render(request, 'wiki_add.html', {'form': form})

    form = WikiModelForm(request, data=request.POST, instance=wiki_object)
    if form.is_valid():
        if form.instance.parent:
            form.instance.depth = form.instance.parent.depth + 1
        else:
            form.instance.depth = 1
        form.save()
        url = reverse('wiki', kwargs={'project_id': project_id})
        # 保存成功后跳转到预览的页面
        preview_url = f'{url}?wiki_id={wiki_id}'
        return redirect(preview_url)

    return render(request, 'wiki_add.html', {'form': form})

    # def wiki_detail(request, project_id):
    #     """ 查看文章详细页面 """
    #     return HttpResponse('查看文章详细页面')


@csrf_exempt
def wiki_upload(request, project_id):
    """ makdown插件上传图片 """
    print('ok')
    print(request.FILES)  # 上传的图片信息

    result = {  # markdown 上传成功返回的默认格式
        'success': 0,
        'message': None,
        'url': None
    }

    image_object = request.FILES.get('editormd-image-file')  # 上传的图片对象
    if not image_object:
        result['message'] = '文件不存在'
        return JsonResponse(result)

    ext = image_object.name.split('.')[-1]  # 上传图片的后缀名
    key = f"{uid(request.bug_platform.user.mobile_phone)}.{ext}"  # 为了不重复

    # 文件对象上传到项目的cos桶中
    # 上传成功后 拿到返回图片路径
    image_url = upload_file(
        request.bug_platform.project.bucket,  # 桶名
        request.bug_platform.project.region,  # 区域
        image_object,
        key
    )
    print(image_url)
    # return JsonResponse({'status': True, "data": image_url})

    # 上传成功后给mardown 说明上传成功 ，不要提示【返回给mardown

    result['success'] = 1
    result['url'] = image_url
    # result = {  # markdown 上传成功返回的默认格式
    #     'success': 1,
    #     'message': None,
    #     'url': image_url
    # }
    return JsonResponse(result)
